import datetime, time
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.db.models import Q
from web.models import User, Group, GroupMember, Notice, Document, DocumentUser
from web.db.manage_db.manage_user import *
from .user import UserSerializer


class GroupSerializer(serializers.ModelSerializer):
    # write_only=True前端传了，model里面没这个字段
    username = serializers.CharField(write_only=True)
    leaderid = serializers.IntegerField(required=False)
    createdtime = serializers.DateTimeField(required=False)
    # 前端没传但是数据库需要required=False
    class Meta:
        model = Group
        fields = "__all__"
    def create(self, validated_data):
        groupname = validated_data["groupname"]
        user = User.objects.filter(username=validated_data.pop("username")).first()
        leaderid = user.id
        description = validated_data["description"]
        id = get_newid()
        # 使用 Group.objects.create() 方法创建新的 Group 实例时，Django 会自动将 createdtime 字段设置为当前时间。
        new_group = Group.objects.create(id=id, groupname=groupname, createdtime=datetime.datetime.now(),leaderid=leaderid, description=description)
        # new_group_member = GroupMember.objects.create(id=id, group_id=id, user_id=leaderid)
        return new_group


class GroupView(APIView):
    def get(self, request):
        group = Group.objects.all()
        serializer = GroupSerializer(instance=group, many=True)
        return Response(serializer.data)
    def post(self, request):
        """
        /api/creategroup/ 创建群组
        :param request:
        :return:
        """
        serializer = GroupSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "success"})
        else:
            print(serializer.errors)
            return Response({"message": "fail"})

    from rest_framework.decorators import api_view


class GroupDetailView(APIView):
    def put(self, request, id):
        """
        /api/modify_group_info/ 修改群组信息
        :param request:
        :return:
        """
        group_obj = Group.objects.filter(id=id).first()
        serialize = GroupSerializer(instance=group_obj, data=request.data)
        if serialize.is_valid():
            serialize.save()
            return Response(serialize.data)
        else:
            return Response(serialize.errors)

@api_view(['POST'])
def group_created_by_me(request):
    """
    檢查某个群组是否由当前登录用户创建/api/groupiscreatedbyme/
    :param request:
    :return:
    """
    # user=request.user
    username = request.data.get("username")
    user = User.objects.filter(username=username).first()
    all_group = Group.objects.filter(leaderid=user.id)
    serializer = GroupSerializer(instance=all_group, many=True)
    return Response(serializer.data)

@api_view(['POST'])
def mygroup(self, request):
    """
    /api/mygroup/ 显示我加入的group
    :param request:
    :return:
    """
    username = request.data.get("username")
    user = User.objects.filter(username=username).first()
    # 判断当前用户加的所有群
    all_groupmember = GroupMember.objects.filter(user_id=user.id)
    res = []
    for groupmember in all_groupmember:
        group = Group.objects.filter(id=groupmember.group_id)
        if (group.leaderid!=user.id):
            serializer = GroupSerializer(instance=group)
            res.append(serializer.data)

    return Response(res)

@api_view(['POST'])
def groupiscreatedbyme(request):
    """
    查看我当前浏览的团队是否是我创建的/api/group_created_byme/
    :param request:
    :return:
    """
    username = request.data.get("username")
    user = User.objects.filter(username=username).first()
    group = Group.objects.filter(leaderid=user.id, id=request.data.get("groupid")).first()
    if group:
        return Response({"message": "yes"})
    return Response({"message": "no"})

@api_view(['POST'])
def search_group(self, request):
    """
    (未测试)
    通过关键字查找群组（查找别的群组，当前自己没加入）/api/search_group/
    :return:
    """
    user = request.user
    keyword = request.data.get("keyword")
    res = []
    # 在Django ORM中，__（双下划线）用于字段查找。icontains 是一种不区分大小写的包含查找。
    # 所以，groupname__icontains=keyword 会在 groupname 字段中查找包含 keyword 的记录，而且这个查找是不区分大小写的。
    groups = Group.objects.filter(groupname__icontains=keyword)
    for group in groups:
        groupmem = GroupMember.objects.filter(group_id=group.id, user_id=user.id)
        if not groupmem:
            res.append(group)
    serializer = GroupSerializer(instance=res, many=True)
    return Response(serializer.data)


# 在我的group中添加用户，这里的用户是前端判断好的不在该group中的user
# addgroupmember 是处理团队领导邀请用户加入团队,发送一个通知给团队领导，告诉他用户接受了他的邀请,通知的对象是用户
@api_view(['POST'])
def addgroupmember(request):
    # 将新用户的信息添加到数据库中
    userid = request.data.get("userid")
    user = User.objects.filter(id=userid)
    groupid = request.data.get("groupid")
    group = Group.objects.filter(id=groupid)
    id = get_newid()
    GroupMember.objects.create(id=id, group_id=groupid, user_id=userid)

    # 发送信息
    id = get_newid()
    now = datetime.datetime.now()
    send_time = now.strftime("%Y-%m-%d")
    content = user.username + "通过了你的邀请，加入团队("+ group.name+")"
    Notice.objects.create(id=id, sender_id=userid, receiver_id=group.leaderid, document_id=0, group_id=groupid,
                                    send_time=send_time, content=content, type=1)
    # 将团队文档添加到个人文档列表中,这样当前用户可以看到别人写的文档
    all_document = Document.objects.filter(group_id=groupid)
    for document in all_document:
        id = get_newid()
        DocumentUser.objects.create(id=id, document_id=document.id, user_id=userid, last_watch=None, favorited=0,
                                            modified_time=None, type=1)
        del_notice(request.data.get("id"))
        return Response({"message": "success"})


@api_view(['POST'])
# 团队管理者向我发送了加入团队邀请，我拒绝了
def refuse_groupmember(request):
    userid = request.data.get("useid")
    user = User.objects.filter(id=userid)
    groupid = request.data.get("groupid")
    group = Group.objects.filter(id=groupid)
    # 我发送拒绝的信息给管理员
    id = get_newid()
    now = datetime.datetime.now()
    send_time = now.strftime("%Y-%m-%d")
    content = user.username + "拒绝了你的邀请不加入团队(" + group.name + ")"
    notice = Notice(id=id, sender_id=userid, receiver_id=group.leaderid, document_id=0,
                    group_id=groupid, send_time=now, content=content, type=5)
    del_notice(request.data.get("id"))
    return Response({"message": "success"})


# 团队创建者想要邀请需要先检索用户，根据用户名检索，返回所有不在该团队中的检索用户
# tested
@api_view(['POST'])
def queryuser(request):
    keyword = request.data.get("keyword")
    groupid = request.data.get("groupid")
    print(request.data)
    all_user = get_user_by_keyword(keyword)
    print(all_user)
    all_group_user = GroupMember.objects.filter(group_id=groupid)
    res = []
    for user in all_user:
        check = 1
        for group_user in all_group_user:
            if group_user.id == user.id:
                check = 0
                continue
        if check == 1:
            serializer = UserSerializer(instance=user, many=False)
            res.append(serializer.data)
    return Response(res)

# 团队管理者发送邀请信息
@api_view(['POST'])
def invite_user(request):
    userid = request.data.get("userid")
    sender = User.objects.filter(username=request.form.get("leader_usename")).first()
    groupid = request.data.get("groupid")
    group = Group.objects.filter(id=groupid).first()
    # 这里的sender_id不能是group.leaderid，因为这样无法确定是哪个团队的管理员
    notice = Notice.objects.filter(Q(sender_id=sender.id)&Q(receiver_id=userid)&Q(group_id=groupid)&Q(type=2)).first()
    if notice:
        return Response({"message": "success"})
    id = get_newid()
    now = datetime.datetime.now()
    send_time = now.strftime("%Y-%m-%d")
    content = sender.username + "邀请你加入团队(" + group.groupname + ")"
    # 管理员发送邀请信息给用户
    # 注意： 在这段代码中，使用 send_time=now 是正确的，因为它为 send_time 属性提供了一个包含完整日期和时间信息的对象。
    # 使用 send_time=send_time 是不正确的，因为它会将一个只包含年月日的字符串赋值给 send_time 属性，而这个属性需要的是一个具有日期和时间信息的对象。
    new_notice = Notice(id=id, sender_id=group.leaderid, receiver_id=userid, document_id=0, group_id=groupid,
                    send_time=now, content=content, type=2)
    new_notice.save()
    return Response({"message": "success"})


# 团队外用户申请加入某团队
@api_view(['POST'])
def apply_in_group(request):
    user = User.objects.filter(username=request.data.get("username")).first()
    group =Group.objects.filter(groupname=request.data.get("groupname")).first()
    notice = Notice.objects.filter(Q(sender_id=user.id)&Q(receiver_id=group.id)&Q(group_id=group.id))
    if notice:
        return Response({"message":"success"})
    id = get_newid()
    now = datetime.datetime.now()
    content = user.username + "申请加入团队(" + group.groupname + ")"
    Notice.objects.create(id=id, sender_id=user.id, receiver_id=group.leaderid, document_id=0,
                          group_id=group.id, send_time=now, content=content, type=6)
    return Response({"message": "success"})


# 作为团队leader，收到了来自用户的申请，我选择通过他的申请，加人，给申请人发一条消息
# 在我的group中添加用户，这里的用户是前端判断好的不在该group中的user
# 该函数是处理用户申请加入团队的请求，通知的对象是团队领导
@api_view(['POST'])
def accept_application_addgroupmember(request):
    userid = request.data.get("userid")
    user = User.objects.filter(id=userid)
    groupid = request.data.get("groupid")
    group = Group.objects.filter(id=groupid)
    leader = User.objects.filter(id=group.leaderid).first()
    id = get_newid()
    GroupMember.objects.create(id=id, user_id=userid, group_id=groupid)
    # 发送消息给用户
    id = id + 1
    now = datetime.datetime.now()
    content = leader.username + "通过了你的申请，你已加入团队(" + group.groupname + ")"
    Notice.objects.create(id=id, sender_id=leader.id, receiver_id=user.id, document_id=0,
                          group_id=groupid, send_time=now, content=content, type=7)
    del_notice(request.data.get("id"))
    # 将团队的文档列表给用户看(将团队的文档添加到DocumentUser数据库中)
    all_document = Document.objects.filter(group_id=group.id)
    for document in all_document:
        id = get_newid()
        DocumentUser.objects.create(id=id, document_id=document.id, user_id=userid, last_watch=None,
                                    favorited=0, modified_time=None, type=1)
    return Response({"message": "success"})


# 作为团队leader，收到了来自用户的申请，我选择拒绝他的申请，不加人，给申请人发一条消息
@api_view(['POST'])
def refuse_application_addgroupmember(request):
    userid = request.data.get("userid")
    user = User.objects.filter(id=userid)
    groupid = request.data.get("groupid")
    group = Group.objects.filter(id=groupid)
    leader = User.objects.filter(id=group.leaderid)
    # 发送通知
    id = get_newid()
    now = datetime.datetime.now()
    content = leader.username + "拒绝了你的申请，加入团队(" + group.groupname + ")"
    Notice.objects.create(id=id, sender_id=leader.id, receiver_id=userid, document_id=0,
                          group_id=groupid, send_time=now, content=content, type=8)
    del_notice(request.data.get("id"))
    return Response({"message": "success"})

class GroupMemberSerializer(serializers.ModelSerializer):
    class Meta:
        model = GroupMember
        fields = "__all__"
# 显示该团队下的成员
@api_view(['POST'])
def get_user_bygroup(request):
    print(request.data.get("groupid"))
    all_group_user = GroupMember.objects.filter(group_id=request.data.get("groupid"))
    print(all_group_user)
    res = []
    for user in all_group_user:
        print(user)
        user = User.objects.filter(id=user.user_id).first()
        res.append(user)
    print(res)
    serializer = UserSerializer(instance=res, many=True)
    return Response(serializer.data)

# 删除团队成员(不知道有几个管理员，这里默认团队创建者就是管理员)
@api_view(['POST'])
def delete_user(request):
    userid = request.data.get("userid")
    user = User.objects.filter(id=userid)
    groupid = request.data.get("groupid")
    group = Group.objects.filter(id=groupid)
    leader = User.objects.filter(id=group.leaderid)
    GroupMember.objects.filter(user_id=userid).delete()
    # 发送消息
    now = datetime.datetime.now()
    id = get_newid()
    content =  leader.username + "将你提出了团队(" + group.groupname + ")"
    Notice.objects.create(id=id, sender_id=leader.id, receiver_id=userid, document_id=0, group_id=groupid,
                          send_time=now, content=content, type=0)
    # 删除成员对应的文档权限
    all_document = Document.objects.filter(group_id=groupid).filter()
    for document in all_document:
        DocumentUser.objects.filter(document_id=document.id, userid=userid).delete()
    return Response({"message": "success"})

# 团队成员主动退出团队
@api_view(['POST'])
def quit_group(request):
    userid = request.data.get("userid")
    user = User.objects.filter(id=userid)
    groupid = request.data.get("groupid")
    group = Group.objects.filter(id=groupid)
    GroupMember.objects.filter(user_id=userid).delete()
    # 发消息
    now = datetime.datetime.now()
    id = get_newid()
    content = user.username + "退出了团队(" + group.groupname + ")"
    Notice.objects.create(id=id, sender_id=userid, receiver_id=group.leaderid, document_id=0, group_id=groupid,
                          send_time=now, content=content, type=9)
    # 删除成员对应的文档权限
    all_document = Document.objects.filter(group_id=groupid)
    for document in all_document:
        DocumentUser.objects.filter(document_id=document.id, userid=userid).delete()
    return Response({"message": "success"})


# 解散团队
@api_view(['POST'])
def delete_group(request):
    groupid = request.data.get("groupid")
    # 删除团队成员
    GroupMember.objects.filter(group_id=groupid)
    # 删除群组
    Group.objects.filter(id=groupid).delete()
    # 删除成员对应文档
    # 删除团队文档
    all_document = Document.objects.filter(group_id=groupid)
    for document in all_document:
        DocumentUser.objects.filter(document_id=document.id).delete()
    Document.objects.filter(group_id=groupid).delete()
    return Response({"message": "success"})




























